/**
 * Written by Nicholas Hillier Dec 20, 2008
 *  
*/
package com.ghostmonk.ui.idecomposed
{
	import com.ghostmonk.events.PercentageEvent;
	
	import flash.display.*;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	public class Scroller extends EventDispatcher
	{
		private var _min:Number;
		private var _max:Number;
			
		private var _playHead:Sprite;
		private var _track:Sprite;
		private var _playHeadTrack:MovieClip;
		
		private var _trackWidth:Number;
		
		private var _pause:Function;
		private var _play:Function;
		
		public function Scroller(playHeadTrack:MovieClip, pause:Function, play:Function)
		{
			_playHead = playHeadTrack.playHead;
			_pause = pause;
			_play = play;
			_track = playHeadTrack.track;
			_playHeadTrack = playHeadTrack;
			
			_trackWidth = _track.width - _playHead.width;
			
			enable();
			
			_min = _track.x + _playHead.width/2;
			_max = _track.x + _track.width - _playHead.width/2; 
		}
		
		public function enable():void
		{
			_playHead.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_playHead.buttonMode = true;
		}
		
		public function disable():void
		{
			_playHead.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			_playHead.buttonMode = false;
		}
		
		public function onLoad(percent:Number):void
		{
			_track.scaleX = percent;
		}
		
		public function setScrubber(percent:Number):void
		{
			var setX:Number = _trackWidth*percent + _playHead.width/2;
			_playHead.x = Math.max(_min, Math.min(_max, setX));
		}
		
		private function onMouseDown(e:MouseEvent):void
		{
			_pause(e);
			_playHead.stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			_playHead.stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function onMouseUp(e:MouseEvent):void
		{
			_play(e);
			_playHead.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
			_playHead.stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
		}
		
		private function onMouseMove(e:MouseEvent):void
		{
			_playHead.x = Math.max(_min, Math.min(_max, _playHeadTrack.mouseX));
			dispatchEvent(new PercentageEvent(PercentageEvent.CHANGE, (_playHead.x - (_playHead.width/2))/_trackWidth));
		}

	}
}